package com.ok.prize.service.impl;

import com.ok.api.client.IntegralClient;
import com.ok.api.client.UserClient;
import com.ok.api.domain.dto.OkIntegralDetailDTO;
import com.ok.api.domain.po.OkUser;
import com.ok.common.config.IntegralNum;
import com.ok.common.domain.po.Result;
import com.ok.common.exception.CustomException;
import com.ok.common.utils.UserContext;
import com.ok.prize.domain.po.OkPrize;
import com.ok.prize.domain.po.OkUserprize;
import com.ok.prize.mapper.OkUserprizeMapper;
import com.ok.prize.service.IOkPrizeService;
import com.ok.prize.service.IOkUserprizeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户奖品关系表 服务实现类
 * </p>
 *
 * @author lhw
 * @since 2024-05-06
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OkUserprizeServiceImpl extends ServiceImpl<OkUserprizeMapper, OkUserprize> implements IOkUserprizeService {

    private final IOkPrizeService okPrizeService;
    private final IntegralClient integralClient;
    private final UserClient userClient;
    private final RabbitTemplate rabbitTemplate;

    @Override
    @GlobalTransactional
    public void exchange(Integer prizeId) {
        OkUserprize okUserprize = new OkUserprize();
        okUserprize.setUserId(UserContext.getUser());
        okUserprize.setPrizeId(prizeId);
        //添加用户奖品表
        this.save(okUserprize);

        //得到奖品信息
        OkPrize prize = okPrizeService.getById(prizeId);
        //判断用户积分是否足够
        Result<OkUser> info = userClient.info(UserContext.getUser());
        OkUser user = info.getData();
        if (user.getIntegral() < prize.getIntegral()){
            throw new CustomException("您的积分不足");
        }
        //修改奖品剩余数量
        if (prize.getNum() == 0){
            throw new CustomException("奖品已经没有了");
        }
        prize.setNum(prize.getNum()-1);
        okPrizeService.updateById(prize);

        //扣减用户对应积分
        integralClient.update(-prize.getIntegral());

        //构建积分详情信息
        OkIntegralDetailDTO detailDTO = new OkIntegralDetailDTO();
        detailDTO.setUserId(UserContext.getUser());
        detailDTO.setPrizeId(prizeId);
        detailDTO.setIntegral(-prize.getIntegral());

        try {
            rabbitTemplate.convertAndSend("integral_direct","",detailDTO);
        } catch (AmqpException e) {
            log.error("发送消息添加积分详细失败：{}",e.getMessage());
        }
    }
}
